# -*- coding: utf-8 -*-
# 第一行必须有，否则报中文字符非ascii码错误
import math
import json

import requests

from org01.ggboy.utils import get_sn_url

sk = 'aely5HzAVUkiKbVP0uuHu5nAXtt1Kish'
ak='iaZBqob8Ys6aPwN3U45v60GKnFowQggh'

def wgs84tobd09(GPSLatitude,GPSLongitude):
    queryStr = '/geoconv/v1/?coords={0},{1}&from=1&to=5&ak={2}'.format(GPSLatitude, GPSLongitude, ak)
    baidu_map_api=get_sn_url(queryStr)
    content = requests.get(baidu_map_api).text
    wgs84_address = json.loads(content)
    return (wgs84_address['result'][0]['x'],wgs84_address['result'][0]['y'])

def wgs84togcj02(GPSLatitude,GPSLongitude):
    queryStr = '/geoconv/v1/?coords={0},{1}&from=1&to=3&ak={2}'.format(GPSLatitude, GPSLongitude, ak)
    baidu_map_api=get_sn_url(queryStr)
    content = requests.get(baidu_map_api).text
    gcj02_address = json.loads(content)
    return (gcj02_address['result'][0]['x'],gcj02_address['result'][0]['y'])

# 将WGS84坐标系转换为GCJ02火星坐标系
# 返回坐标字符串lon,lat

pi = 3.1415926535897932384626
a = 6378245.0
ee = 0.00669342162296594323


def wgs_gcj(lat, lon):

    dLat = transform_lat(lon - 105.0, lat - 35.0)
    dLon = transform_lon(lon - 105.0, lat - 35.0)
    radLat = lat / 180.0 * pi
    magic = math.sin(radLat)
    magic = 1 - ee * magic * magic
    sqrtMagic = math.sqrt(magic)
    dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi)
    dLon = (dLon * 180.0) / (a / sqrtMagic * math.cos(radLat) * pi)
    mgLat = lat + dLat
    mgLon = lon + dLon
    return (mgLat,mgLon)


def transform_lat(x, y):

    ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * math.sqrt(abs(x))
    ret += (20.0 * math.sin(6.0 * x * pi) + 20.0 * math.sin(2.0 * x * pi)) * 2.0 / 3.0
    ret += (20.0 * math.sin(y * pi) + 40.0 * math.sin(y / 3.0 * pi)) * 2.0 / 3.0
    ret += (160.0 * math.sin(y / 12.0 * pi) + 320 * math.sin(y * pi / 30.0)) * 2.0 / 3.0
    return ret


def transform_lon(x, y):

    ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * math.sqrt(abs(x))
    ret += (20.0 * math.sin(6.0 * x * pi) + 20.0 * math.sin(2.0 * x * pi)) * 2.0 / 3.0
    ret += (20.0 * math.sin(x * pi) + 40.0 * math.sin(x / 3.0 * pi)) * 2.0 / 3.0
    ret += (150.0 * math.sin(x / 12.0 * pi) + 300.0 * math.sin(x / 30.0 * pi)) * 2.0 / 3.0
    return ret


if __name__ == '__main__':
    print(wgs84tobd09(31.040565490555558,117.07209777805555))
    print(wgs84togcj02(31.040565490555558, 117.07209777805555))
    print(wgs_gcj(31.040565490555558, 117.07209777805555))
